package com.tiennt.android.callnotes;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tiennt.android.callnotes.db.DbAdapter;
import com.tiennt.android.callnotes.utils.ProjectUtils;

public class EditNotesActivity extends Activity {
	// Component
	private EditText txtNoteTitle;
	private EditText txtNoteContent;
	private Button btnSave;
	private Button btnCancel;
	private Button btnSelectContact;
	private TextView tvContact;
	private CheckBox chbxIncoming;
	private CheckBox chbxOutgoing;

	private int itemId;

	private static final int CONTACT_PICKER_RESULT = 1001;
	private final String TAG = "EditNoteActivity";
	private final boolean DBG = true;

	// Variable handle content of each component
	private String noteTitle;
	private String noteContent;
	private String contactId;
	private View.OnClickListener onBtnSaveClick;
	private View.OnClickListener onBtnCancelClick;
	private View.OnClickListener onBtnSelectContactClick;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_note);

		initialComponents();
	}

	private void initialComponents() {
		txtNoteTitle = (EditText) findViewById(R.id.txtNoteTitle);
		txtNoteContent = (EditText) findViewById(R.id.txtNoteContent);

		btnSave = (Button) findViewById(R.id.btnSave);
		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnSelectContact = (Button) findViewById(R.id.btnChangeContact);

		tvContact = (TextView) findViewById(R.id.tvContact);

		chbxIncoming = (CheckBox) findViewById(R.id.chbxIncomming);
		chbxOutgoing = (CheckBox) findViewById(R.id.chbxOutgoing);

		onBtnSaveClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				handleOnBtnSaveClick();
			}
		};

		onBtnCancelClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				handleOnBtnCancelClick();
			}
		};

		onBtnSelectContactClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				handleOnBtnSelectContactClick();
			}
		};

		btnSave.setOnClickListener(onBtnSaveClick);
		btnCancel.setOnClickListener(onBtnCancelClick);
		btnSelectContact.setOnClickListener(onBtnSelectContactClick);

		Bundle data = getIntent().getExtras();

		itemId = data.getInt(ProjectUtils.BUNDLEKEY_ITEMID);
		contactId = data.getString(ProjectUtils.BUNDLEKEY_CONTACTID);

		String contactName = data.getString(ProjectUtils.BUNDLEKEY_CONTACTNAME);
		String title = data.getString(ProjectUtils.BUNDLEKEY_NOTETITLE);
		String content = data.getString(ProjectUtils.BUNDLEKEY_NOTECONTENT);
		boolean in = data.getBoolean(ProjectUtils.BUNDLEKEY_INCOMING);
		boolean out = data.getBoolean(ProjectUtils.BUNDLEKEY_OUTGOING);

		txtNoteTitle.setText(title);
		txtNoteContent.setText(content);
		tvContact.setText(contactName);
		chbxIncoming.setChecked(in);
		chbxOutgoing.setChecked(out);
	}

	private void handleOnBtnSaveClick() {
		noteTitle = txtNoteTitle.getText().toString();
		noteContent = txtNoteContent.getText().toString();

		int incoming = chbxIncoming.isChecked() == true ? 1 : 0;
		int outgoing = chbxOutgoing.isChecked() == true ? 1 : 0;

		if (noteTitle.equals("") || noteContent.equals("")
				|| contactId.equals("")) {
			// TB LOI
		} else {
			int result = 0;
			DbAdapter dbAdapter = new DbAdapter(this);
			dbAdapter.open();

			result = (int) dbAdapter.saveEditedNote(itemId, noteTitle,
					noteContent, contactId, incoming, outgoing);

			dbAdapter.close();

			if (result != 0) {
				Toast.makeText(getApplicationContext(), "Success",
						Toast.LENGTH_SHORT).show();
				setResult(RESULT_OK);
				this.finish();
			} else {
				Toast.makeText(getApplicationContext(), "Failure",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public void onBackPressed() {
		promptOnFinish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CONTACT_PICKER_RESULT:
				// handle contact results
				String contactName = "";
				Cursor cursor = null;
				try {
					Uri result = data.getData();
					log("Got a contact result: " + result.toString());
					// get the contact id from the Uri
					contactId = result.getLastPathSegment();
					log("Got a contact result: " + contactId);

					Uri contactUri = ContentUris.withAppendedId(
							ContactsContract.Contacts.CONTENT_URI,
							Long.parseLong(contactId));

					cursor = managedQuery(contactUri, null, null, null, null);

					if (cursor.moveToFirst()) {
						contactName = cursor
								.getString(cursor
										.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					}
					log("Display name: " + contactName);
				} catch (Exception e) {
					// TODO: handle exception
					log("Unexpected exception occurred");
				}

				tvContact.setText(contactName);

				break;
			}
		} else {
			// gracefully handle failure
			log("Warning: activity result not ok");
		}
	}

	private void handleOnBtnCancelClick() {
		promptOnFinish();
	}

	private void handleOnBtnSelectContactClick() {
		Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
				Contacts.CONTENT_URI);
		startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);

	}

	private void promptOnFinish() {
		if (!txtNoteTitle.getText().toString().equals("")
				|| !txtNoteContent.getText().toString().equals("")) {

			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("Discard?");
			alert.setMessage("Your changes are unsaved. Do you want to save the note?");

			alert.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							// Save the note
							handleOnBtnSaveClick();
						}
					});

			alert.setNegativeButton("No",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							setResult(RESULT_CANCELED);
							EditNotesActivity.this.finish();
						}
					});
			alert.create().show();
		} else {
			EditNotesActivity.this.finish();
		}
	}

	public void log(String msg) {
		if (DBG) {
			Log.d(TAG, msg);
		}
	}
}
